package exchange;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * TODO
 *
 * @author gaoxiang
 * @date 2021/7/2723:19
 */
public class ExchangeReceive1 {
    public static void main(String[] args) throws Exception {
        //创建链接工厂对象
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("121.41.192.69");//设置RabbitMQ的主机IP
        factory.setPort(5672);//设置RabbitMQ的端口号
        factory.setUsername("guest");//设置访问用户名
        factory.setPassword("guest");//设置访问密码
        Connection connection = null;//定义链接对象
        Channel channel = null;//定义通道对象
        connection = factory.newConnection();//实例化链接对象
        channel = connection.createChannel();//实例化通道对象
        channel.queueDeclare("Queue_3_1", true, false, false, null);
        //指定Exchange的类型
        //参数1为 交换机名称
        //参数2为交换机类型取值为 direct、queue、topic、headers
        //参数3 为是否为持久化消息 true表示持久化消息 false表示非持久化
        channel.exchangeDeclare("Exchange_1", BuiltinExchangeType.DIRECT, true);
        //队列绑定交换机-channel.queueBind(队列名, 交换机名, 路由key[广播消息设置为空串])
        channel.queueBind("Queue_3_1", "Exchange_1", "log.error");

        channel.basicConsume("Queue_3_1", true, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag,
                                       Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                //获取消息数据
                String bodyStr = new String(body, "UTF-8");
                System.out.println(bodyStr);
            }
        });
//            channel.close();
//            conn.close();


    }
}
